28.Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = “hello”, needle = “ll”
Output: 2
Example 2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
Clarification:
What should we return when needle is an empty string? This is a great question to ask during an interview.
For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().
三种解法,首先是暴力解法,本来我先写了这个解法试试看,结果leetcode没通过,在倒数第二个case时超时了,在处理aaaa…ab, aa…ab(非常多个a)这种情况时,时间复杂度时n*m,显然不是一个很好的算法,使用KMP算法只有O(n+m)。
感谢UP主 [KMP算法]NEXT数列手算演示
1 | 暴力破解法: |
1 | KMP算法: |
使用KMP算法运算速率成功的打败了100%的人,然后点了
sample 0 ms submission,看到了别人的算法。。。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17int strStr(char* haystack, char* needle) {
int a = strlen(needle);
int b = strlen(haystack);
if(a==0)
return 0;
for(int i=0;i<b-a+1;i++){
for(int j = 0; j<b; j++){
if(haystack[i+j] == needle[j]){
if(j == a-1)
return i;
}
else
break;
}
}
return -1;
}